package com.pri.chat.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.location.AMapLocation;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.net.SharedHelper;
import com.netease.nim.uikit.net.entity.BaseBean;
import com.netease.nim.uikit.net.entity.KeFuEntity;
import com.netease.nim.uikit.net.rxjava.HttpMethods;
import com.netease.nim.uikit.net.subscribers.ProgressSubscriber;
import com.netease.nim.uikit.net.subscribers.SubscriberOnNextListener;
import com.pri.chat.MainActivity;
import com.pri.chat.R;
import com.pri.chat.adapter.DialogSignAdapter;
import com.pri.chat.adapter.GridImageAdapter;
import com.pri.chat.dialog.CommunitySelector;
import com.pri.chat.event.EventTag;
import com.pri.chat.event.MessageEvent;
import com.pri.chat.model.DTMsgModel;
import com.pri.chat.utils.Auth;
import com.pri.chat.utils.Des3Util;
import com.pri.chat.utils.GlideEngine;
import com.pri.chat.utils.LocationUtil;
import com.pri.chat.utils.StringUtils;
import com.pri.chat.utils.TimeUtils;
import com.pri.chat.utils.bars.StatusBarUtil;
import com.qiniu.android.storage.UploadManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.vondear.rxui.view.dialog.RxDialogLoading;
import com.vondear.rxui.view.progressing.SpriteFactory;
import com.vondear.rxui.view.progressing.Style;
import com.vondear.rxui.view.progressing.sprite.Sprite;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 描述：添加类的描述
 *
 * @author wx5e48d604c2885118
 * @time 2020/4/8
 */
public class ReleaseWishAcctivity extends AppCompatActivity {
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.wish_image)
    ImageView wish_image;
    @BindView(R.id.tv_release)
    TextView tvRelease;
    @BindView(R.id.sfgkImg)
    ImageView sfgkImg;
    @BindView(R.id.address)
    TextView address;
    @BindView(R.id.xzqxTv)
    TextView xzqxTv;
    @BindView(R.id.xzbqTv)
    TextView xzbqTv;

    @BindView(R.id.xzqxLinear)
    LinearLayout xzqxLinear;
    @BindView(R.id.cancelTv)
    TextView cancelTv;
    @BindView(R.id.wqxTv)
    TextView wqxTv;
    @BindView(R.id.ybzTv)
    TextView ybzTv;
    @BindView(R.id.ywnTv)
    TextView ywnTv;
    @BindView(R.id.zheCeng)
    View zheCeng;




    private Activity activity;
    private Context context;
    /**
     * 图纸图片
     */
//    private GridImageAdapter mPostAdapter;
    private List<LocalMedia> localMediaList = new ArrayList<>();//个人荣誉
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = () -> {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle())// 自定义相册启动退出动画
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项   参考Demo MainActivity中代码
                //   .isOriginalImageControl(cb_original.isChecked())// 是否显示原图控制按钮，如果用户勾选了 压缩、裁剪功能将会失效
                .isWeChatStyle(true)// 是否开启微信图片选择风格，此开关开启了才可使用微信主题！！！
                .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效
                .maxSelectNum(9)// 最大图片选择数量 int
                .minSelectNum(1)// 最小选择数量 int
                .imageSpanCount(3)// 每行显示个数 int
                .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .queryMaxFileSize(50)// 只查多少M以内的图片、视频、音频  单位M
                //   .querySpecifiedFormatSuffix(PictureMimeType.ofPNG())// 查询指定后缀格式资源
                //   .cameraFileName("test.png") // 重命名拍照文件名、注意这个只在使用相机时可以使用
                //   .renameCompressFile("test.png")// 重命名压缩文件名、 注意这个不要重复，只适用于单张图压缩使用
                //   .renameCropFileName("test.png")// 重命名裁剪文件名、 注意这个不要重复，只适用于单张图裁剪使用
                //   .isSingleDirectReturn(false)// 单选模式下是否直接返回，PictureConfig.SINGLE模式下有效
                .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                .previewImage(true)// 是否可预览图片 true or false
                .isCamera(true)// 是否显示拍照按钮 true or false
                .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                .enableCrop(false)// 是否裁剪 true or false
                .compress(true)// 是否压缩 true or false
                .isGif(true)// 是否显示gif图片 true or false
                //   .compressSavePath(getPath())//压缩图片保存地址
                .openClickSound(false)// 是否开启点击声音 true or false
                .selectionMedia(localMediaList)// 是否传入已选图片 List<LocalMedia> list
                .cutOutQuality(90)// 裁剪输出质量 默认100
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    };

    private String fromType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_release_wish_layout);
        StatusBarUtil.setStatusBarMode(this, true, R.color.white);
        activity = this;
        context = this;
        ButterKnife.bind(this);
        initView();
        getItemSign();
        initStartTimePicker();
        initCommentDialog();
    }

    private void initView() {
        if (getIntent().getExtras() != null) {
            fromType = getIntent().getExtras().getString("type");
        }
        initLoadingDialog();
        lat = SharedHelper.readValueByKeyForString(this, "lat");
        lng = SharedHelper.readValueByKeyForString(this, "lng");
        province = SharedHelper.readValueByKeyForString(this, "province");
        city = SharedHelper.readValueByKeyForString(this, "city");
        area = SharedHelper.readValueByKeyForString(this, "area");
        address.setText(province + city + area);
        initLoc();
    }


    private String lat, lng, province, city, area;
    private LocationUtil locationUtil;

    private void initLoc() {
        locationUtil = new LocationUtil(this);
        locationUtil.dingwei();
        locationUtil.setOnLocChangedListener(new LocationUtil.OnLocChangedListener() {
            @Override
            public void onLocationChanged(AMapLocation loc) {
                Log.i("城市：", loc.getCity());
                province = loc.getProvince();
                city = loc.getCity();
                area = loc.getDistrict();
                lat = loc.getLatitude() + "";
                lng = loc.getLongitude() + "";

                SharedHelper.saveKeyValueForString(ReleaseWishAcctivity.this, "province", loc.getProvince() + "");
                SharedHelper.saveKeyValueForString(ReleaseWishAcctivity.this, "area", loc.getDistrict() + "");
                SharedHelper.saveKeyValueForString(ReleaseWishAcctivity.this, "lat", loc.getLongitude() + "");
                SharedHelper.saveKeyValueForString(ReleaseWishAcctivity.this, "lat", loc.getLongitude() + "");
                SharedHelper.saveKeyValueForString(ReleaseWishAcctivity.this, "city", loc.getCity());
                address.setText(loc.getAddress());

                locationUtil.stopLocation();
                locationUtil.destroyLocation();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            switch (requestCode) {
            case PictureConfig.CHOOSE_REQUEST:
                // 图片选择结果回调
                if (!PictureSelector.obtainMultipleResult(data).isEmpty()) {
                    localMediaList.clear();
                    localMediaList.addAll(PictureSelector.obtainMultipleResult(data));
//                    mPostAdapter.notifyDataSetChanged();
//                    httpUpImgMulti(list);

                    Glide.with(activity)
                            .load(localMediaList.get(0).getPath())
                            .centerCrop()
                            .into(wish_image);

                }
                break;
            case 5:
                String sign = data.getStringExtra("sign");
                xzbqTv.setText(sign);
                break;

        }
        }
    }


    private static final String TAG = "ReleaseDTActivity";
    private UploadManager uploadManager = new UploadManager();

    private void uploadImg(String data, int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String key = "img_" + i + sdf.format(new Date());
        String token = "ayjstx";
        uploadManager.put(data, key, Auth.create(HttpMethods.ACCESS_KEY, HttpMethods.SECRET_KEY).uploadToken(token),
                (key1, info, res) -> {
                    //res包含hash、key等信息，具体字段取决于上传策略的设置
                    if (info.isOK()) {
                        Log.i("qiniu", "Upload Success");
                        Log.d(TAG, "complete: " + HttpMethods.QN_PATH + key1);
                        if (i == 0) {
                            mImgPath = HttpMethods.QN_PATH + key1;
                        } else {
                            mImgPath = mImgPath + "," + HttpMethods.QN_PATH + key1;
                        }
                        if (i == localMediaList.size() - 1) {
                            rxDialogLoading.dismiss();
                            httpReleaseDT();
                        } else {
                            uploadImg(localMediaList.get(i + 1).getCompressPath(), i + 1);
                        }

                    } else {
                        Log.i("qiniu", "Upload Fail");
                    }
                    Log.i("qiniu", key1 + ",\r\n " + info + ",\r\n " + res);
                }, null);
    }

    private RxDialogLoading rxDialogLoading;

    private void initLoadingDialog() {
        rxDialogLoading = new RxDialogLoading(this);
        Sprite sprite = SpriteFactory.create(Style.THREE_BOUNCE);//设置style
        rxDialogLoading.getLoadingView().setIndeterminateDrawable(sprite);
        rxDialogLoading.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        rxDialogLoading.setCancelable(false);//设置是否可取消
    }


    TimePickerView mStartDatePickerView;

    /**
     * 初始化开始日期选择器控件
     */
    private void initStartTimePicker() {
        //控制时间范围(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
        //因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
        Calendar selectedDate = TimeUtils.strToCalendar(xzqxTv.getText().toString());
        //设置最小日期和最大日期
        Calendar startDate = Calendar.getInstance();
        Calendar endDate = Calendar.getInstance();
        try {
            startDate.setTime(TimeUtils.strToDate(TimeUtils.getCurrentTime()));//设置为2006年4月28日
            endDate.setTime(TimeUtils.strToDate("2050-12-31"));//设置为2006年4月28日
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //时间选择器
        mStartDatePickerView = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                // 这里回调过来的v,就是show()方法里面所添加的 View 参数，如果show的时候没有添加参数，v则为null
                xzqxTv.setText(TimeUtils.dataToStr(date, "yyyy-MM-dd"));
            }
        })
//                .setDecorView((RelativeLayout)findViewById(R.id.activity_rootview))//必须是RelativeLayout，不设置setDecorView的话，底部虚拟导航栏会显示在弹出的选择器区域
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false)//是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTitleText("选择日期")//标题文字
                .setTitleSize(20)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.color_333333))//标题文字颜色
                .setCancelText("取消")//取消按钮文字
                .setCancelColor(getResources().getColor(R.color.color_666666))//取消按钮文字颜色
                .setSubmitText("确定")//确认按钮文字
                .setSubmitColor(getResources().getColor(R.color.orange))//确定按钮文字颜色
                .setContentTextSize(20)//滚轮文字大小
                .setTextColorCenter(getResources().getColor(R.color.orange))//设置选中文本的颜色值
                .setLineSpacingMultiplier(1.8f)//行间距
                .setDividerColor(getResources().getColor(R.color.gray))//设置分割线的颜色
                .setRangDate(startDate, endDate)//设置最小和最大日期
                .setDate(selectedDate)//设置选中的日期
                .build();
    }


    Dialog mCommentDialog;
    private SmartRefreshLayout mSrlComment;
    private RecyclerView mRvComment;
    private int comment_page = 1;
    private List<KeFuEntity> mCommentList = new ArrayList<>();
    private DialogSignAdapter mCommentAdapter;

    private void initCommentDialog() {
        mCommentDialog = new Dialog(this, R.style.Theme_Light_Dialog);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_sign, null);
        mSrlComment = dialogView.findViewById(R.id.srl_comment);
        mRvComment = dialogView.findViewById(R.id.rec_comment);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        mRvComment.setLayoutManager(linearLayoutManager);
        mRvComment.setNestedScrollingEnabled(false);
        mCommentAdapter = new DialogSignAdapter(R.layout.item_sign, mCommentList);
        mRvComment.setAdapter(mCommentAdapter);
        //获得dialog的window窗口
        Window window = mCommentDialog.getWindow();
        WindowManager wm = getWindowManager();
        //设置dialog在屏幕底部
        window.setGravity(Gravity.BOTTOM);
        //设置dialog弹出时的动画效果，从屏幕底部向上弹出

        window.setWindowAnimations(R.style.dialogStyle);
        window.getDecorView().setPadding(0, 0, 0, 0);
        //获得window窗口的属性
        WindowManager.LayoutParams lp = window.getAttributes();
        //设置窗口宽度为充满全屏
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置窗口高度为包裹内容
        lp.height = 1200;
        //将设置好的属性set回去
        window.setAttributes(lp);
        //将自定义布局加载到dialog上
        mCommentDialog.setContentView(dialogView);
        mCommentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                xzbqTv.setText(mCommentList.get(position).getValue());
                mCommentDialog.dismiss();
            }
        });
    }


    private String mImgPath = "";
    private int type = 0; //默认是公开

    @OnClick({R.id.xzqxTv, R.id.xzbqTv, R.id.iv_back, R.id.tv_release, R.id.wish_image, R.id.sfgkImg,R.id.zheCeng,R.id.cancelTv,R.id.wqxTv,R.id.ybzTv,R.id.ywnTv,R.id.jtrqTv})
    public void onViewClicked(View view) {
        if(R.id.zheCeng == view.getId() || R.id.cancelTv == view.getId()){
            zheCeng.setVisibility(View.GONE);
            xzqxLinear.setVisibility(View.GONE);
        }else if(R.id.wqxTv == view.getId()){
            zheCeng.setVisibility(View.GONE);
            xzqxLinear.setVisibility(View.GONE);
            xzqxTv.setText("无期限");
        }else if(view.getId() == R.id.ybzTv){
            zheCeng.setVisibility(View.GONE);
            xzqxLinear.setVisibility(View.GONE);
            xzqxTv.setText("一辈子");
        }else if(view.getId() == R.id.ywnTv){
            zheCeng.setVisibility(View.GONE);
            xzqxLinear.setVisibility(View.GONE);
            xzqxTv.setText("一万年");
        }else if(view.getId() == R.id.jtrqTv){
            zheCeng.setVisibility(View.GONE);
            xzqxLinear.setVisibility(View.GONE);
            mStartDatePickerView.show();
        }else if (R.id.xzqxTv == view.getId()) {
            //年月日
            zheCeng.setVisibility(View.VISIBLE);
            xzqxLinear.setVisibility(View.VISIBLE);
        } else if (R.id.xzbqTv == view.getId()) {
            //选择标签
//            mCommentDialog.show();
            RxActivityTool.skipActivityForResult(this, SelectSignActivity.class,5);
        } else if (R.id.tv_release == view.getId()) {
            if (StringUtils.isEmpty(etContent.getText().toString())) {
                RxToast.normal("请输入内容");
                return;
            }
            if (localMediaList.isEmpty()) {
                RxToast.normal("请上传图片");
                return;
            }
            if (StringUtils.isEmpty(xzbqTv.getText().toString())) {
                RxToast.normal("请选择标签");
                return;
            }
            if (StringUtils.isEmpty(xzqxTv.getText().toString())) {
                RxToast.normal("请选择期限");
                return;
            }
            rxDialogLoading.show();
            uploadImg(localMediaList.get(0).getCompressPath(), 0);
        } else if (view.getId() == R.id.wish_image) {
            PictureSelector.create(this)
                    .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .setPictureWindowAnimationStyle(new PictureWindowAnimationStyle())// 自定义相册启动退出动画
                    .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项   参考Demo MainActivity中代码
                    .isWeChatStyle(true)// 是否开启微信图片选择风格，此开关开启了才可使用微信主题！！！
                    .isAndroidQTransform(true)// 是否需要处理Android Q 拷贝至应用沙盒的操作，只针对compress(false); && enableCrop(false);有效
                    .maxSelectNum(1)// 最大图片选择数量 int
                    .minSelectNum(1)// 最小选择数量 int
                    .imageSpanCount(3)// 每行显示个数 int
                    .isNotPreviewDownload(true)// 预览图片长按是否可以下载
                    .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                    .queryMaxFileSize(50)// 只查多少M以内的图片、视频、音频  单位M
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                    .previewImage(true)// 是否可预览图片 true or false
                    .isCamera(true)// 是否显示拍照按钮 true or false
                    .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                    .enableCrop(false)// 是否裁剪 true or false
                    .compress(true)// 是否压缩 true or false
                    .isGif(true)// 是否显示gif图片 true or false
                    .openClickSound(false)// 是否开启点击声音 true or false
                    .selectionMedia(localMediaList)// 是否传入已选图片 List<LocalMedia> list
                    .cutOutQuality(90)// 裁剪输出质量 默认100
                    .minimumCompressSize(100)// 小于100kb的图片不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        } else if (view.getId() == R.id.iv_back) {
            if ("1".equals(fromType)) {
                RxActivityTool.skipActivity(this, MainActivity.class);
            }
            finish();
        } else if (view.getId() == R.id.sfgkImg) {
            if (type == 0) {
                type = 1;
                sfgkImg.setImageResource(R.mipmap.ic_kg_guan);
            } else {
                type = 0;
                sfgkImg.setImageResource(R.mipmap.ic_kg_kai);
            }
        }
    }

    private void httpReleaseDT() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            Log.d(TAG, "onNext: " + baseBean.toString());
            RxToast.normal("发布成功");
            MessageEvent messageEvent = new MessageEvent(EventTag.WISH, "");
            EventBus.getDefault().post(messageEvent);
            if("1".equals(fromType)){
                RxActivityTool.skipActivity(this,MainActivity.class);
            }
            finish();
        };
        DTMsgModel dtMsgModel = new DTMsgModel();
        dtMsgModel.setContent(etContent.getText().toString());
        dtMsgModel.setMemberId(SharedHelper.readId(this));
        dtMsgModel.setPicList(mImgPath);
        dtMsgModel.setType(type);
        dtMsgModel.setProvince(province);
        dtMsgModel.setCity(city);
        dtMsgModel.setArea(area);
        dtMsgModel.setLat(lat);
        dtMsgModel.setLng(lng);
        dtMsgModel.setBiaoqian(xzbqTv.getText().toString());
        dtMsgModel.setQixian(xzqxTv.getText().toString());
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(dtMsgModel));
        HttpMethods.getInstance().createWish(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }

    private void getItemSign() {
        SubscriberOnNextListener<BaseBean<List<KeFuEntity>>> onNextListener = baseBean -> {
            mCommentList.clear();
            mCommentList.addAll(baseBean.getData());
            mCommentAdapter.notifyDataSetChanged();
        };
        Map<String, Object> params = new HashMap<>();
        params.put("code", "wishSignCode");
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), Des3Util.getJiaMi(params));
        HttpMethods.getInstance().getDictionaryItemList(new ProgressSubscriber<>(onNextListener, this, true), requestBody);
    }
}
